package clusterutil

import (
	"context"
	"strings"

	"gopkg.openfuyao.cn/bkecommon"
	confv1beta1 "gopkg.openfuyao.cn/bkecommon/cluster/api/v1beta1"
	bkenode "gopkg.openfuyao.cn/bkecommon/cluster/node"
	corev1 "k8s.io/api/core/v1"
	"sigs.k8s.io/controller-runtime/pkg/client"

	"gopkg.openfuyao.cn/cluster-api-provider-bke/utils"
)

func AvailableLoadBalancerEndPoint(endPoint confv1beta1.APIEndpoint, nodes bkenode.Nodes) bool {
	if endPoint.IsValid() {
		host := endPoint.Host
		if nodes.Filter(bkenode.FilterOptions{"IP": host}).Length() == 0 {
			return true
		}
	}
	return false
}

// GetIngressConfig 获取bkecluster ingress(ELB) addon配置
func GetIngressConfig(addons []confv1beta1.Product) (lbVIP string, lbNodes []string) {
	var elbAddon *confv1beta1.Product
	for _, addon := range addons {
		if addon.Name == "beyondELB" {
			elbAddon = &addon
			break
		}
	}
	if elbAddon != nil {
		lbVIP = elbAddon.Param["lbVIP"]
		lbNodes = strings.Split(elbAddon.Param["lbNodes"], ",")
		// 去除空字符串
		lbNodes = utils.TrimSpaceSlice(lbNodes)
	}
	return
}

func BKEConfigCmKey() client.ObjectKey {
	return client.ObjectKey{
		Namespace: "cluster-system",
		Name:      bkecommon.BKEClusterConfigFileName,
	}
}

func GetBKEConfigCMData(ctx context.Context, c client.Client) (map[string]string, error) {
	config := &corev1.ConfigMap{}
	err := c.Get(ctx, BKEConfigCmKey(), config)
	if err != nil {
		return nil, err
	}
	return config.Data, nil
}
